/* 
 * Copyright 2013 Share.Ltd  All rights reserved.
 * Share.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * @StringUtil.java - 2013-4-17 3:47:49 - Carson2440 
 * @author YanXu Email:981385016@qq.com
 * @version 1.0
 */

package com.share.lottery.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.util.LogUtils;
import com.share.lottery.base.BaseApplication;
import com.share.lottery.view.CustomToast;

public class StringUtil {
	public final static String REG_DIGIT = "[0-9]*";
	public final static DecimalFormat df = new DecimalFormat(".#");
	public static final String FORMAT_0 = "yyyy-MM-dd HH:mm:ss";
	private static DateFormat sdf_all = new SimpleDateFormat(FORMAT_0);
	
	public static final String FORMAT_1 = "yyyy-MM-dd HH:mm";
	private static DateFormat sdf_all2 = new SimpleDateFormat(FORMAT_1);

	public static boolean isNullOrEmpty(CharSequence text) {
		if (text == null || text.length() == 0) {
			return true;
		}
		return false;
	}

	public static boolean checkPhoneNumber(String phone) {
		if (StringUtil.isNullOrEmpty(phone)) {
			return false;
		} else {

			if (StringUtil.isDigit(phone) && phone.length() == 11) {

			} else {
				return false;
			}
		}
		return true;
	}

	public static boolean isDigit(String str) {
		return str.matches("[0-9]*");
	}

	/**
	 * 判断是否为手机号
	 * 
	 * @param mobile
	 * @return
	 */
	public static boolean isMobile(String mobile) {
		String regex = "^(13[0-9]|15[0-9]|18[0-9]|14[0-9])\\d{8}$";
		if (!isMatch(regex, mobile)) {
			return false;
		}
		return true;
	}

	/** 判断是否找得到字符 */
	private static boolean isMatch(String reg, String text) {
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(text);
		if (m.find())
			return true;
		else
			return false;
	}

	public static boolean checkPhone(String phone) {
		return phone.matches("(^(\\d{3,4}-)?\\d{7,8})$|(13[0-9]{9})");
	}

	public static boolean checkPass(String pass) {
		return pass.matches("^[^\\s\\u4e00-\\u9fa5]{4,20}$");
	}

	public static boolean checkEmail(String email) {
		return email
				.matches("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
	}

	/**
	 * 判断是英文或数字
	 * 
	 * @param
	 * @return
	 */
	public static boolean checkIsNumOrAl(String pwd) {
		return pwd.matches("^[A-Za-z0-9]+$");
	}

	public static boolean checkMoney(String money) {
		return money.matches("^(([1-9]\\d*)|0)(\\.\\d{1,2})?$");
	}

	public static Calendar timeToCalendar(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date;
		Calendar calendar = Calendar.getInstance();
		try {
			date = sdf.parse(time);
			calendar.setTime(date);
		} catch (ParseException e) {
			e.printStackTrace();
			calendar.set(Calendar.DATE, 1);
		}
		return calendar;
	}

	public static String phoneAccCode(Context context) {
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String accCode = telephonyManager.getDeviceId();
		return accCode;
	}

	public static boolean checkIsPhone(String phone) {
		String regEx = "^[0-9_]";
		return phone.matches(regEx);
	}

	public static String getHashName(String url) {
		if (url == null) {
			return "NULL";
		} else {
			return url.replaceAll("[/\\\\.:*,?]", "_").replaceAll("[_]_", "_");
		}
	}

	/**
	 * 把map转化为params
	 * 
	 * @param map
	 *            LinkedHashMap
	 * @return
	 */
	public static String getMapParams(LinkedHashMap<String, String> map) {
		StringBuffer str = new StringBuffer();

		if (map != null && map.size() > 0) {

			for (Map.Entry<String, String> entry : map.entrySet()) {
				str.append("&");
				str.append(entry.getValue());
			}

		}

		return str.toString();
	}

	/**
	 * 清除文字
	 * 
	 * @param cont
	 * @param editer
	 */
	public static void showClearWordsDialog(final Context cont,
			final EditText editer, final TextView numwords) {
		AlertDialog.Builder builder = new AlertDialog.Builder(cont);
		builder.setTitle("要清空输入的内容吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// 清除文字
				editer.setText("");
				numwords.setText("140");
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	/**
	 * 清除文字
	 * 
	 * @param cont
	 * @param editer
	 */
	public static void showClearWordsDialog(final Context cont,
			final EditText editer, final TextView numwords, final int maxLenth) {
		AlertDialog.Builder builder = new AlertDialog.Builder(cont);
		builder.setTitle("要清空输入的内容吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// 清除文字
				editer.setText("");
				numwords.setText(maxLenth + "");
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	/**
	 * 把时间戳转换为微博时间
	 * 
	 * @param time2
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("SimpleDateFormat")
	public static String getWeiBoTime(String dateStr) {
		long time2 = dateToMillsOne(dateStr);

		Date now = new Date();
		long day = 0;// 天数
		long hour = 0;// 小时
		long min = 0;// 分钟
		long sec = 0;// 秒
		try {
			long time1 = now.getTime();
			// time2 = time2 * 1000l;
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000));
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String rs = "";
		// if (hour == 0) {
		// rs = min + "分钟前";
		// return rs;
		// }
		// if (day == 0 && hour <= 4) {
		// rs = hour + "小时前";
		// return rs;
		// }
		SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");//
		String d = format.format(time2);
		Date date = null;
		try {
			date = format.parse(d);// 把字符类型的转换成日期类型的！
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (now.getDate() - date.getDate() == 0) {// 当前时间和时间戳转换来的时间的天数对比
			DateFormat df2 = new SimpleDateFormat("HH:mm");
			rs = "今天  " + df2.format(time2);
			return rs;
		} else if (now.getDate() - date.getDate() == 1) {
			DateFormat df2 = new SimpleDateFormat("HH:mm");
			rs = "昨天  " + df2.format(time2);
			return rs;
		} else {
			DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			rs = df2.format(time2);
			return rs;
		}
	}
	
	/**
	 * 处理格式为HH:mm的
	 * @param dateStr
	 * @return
	 */
	public static String getWeiBoTime1(String dateStr) {
		long time2 = dateToMillsTwo(dateStr);

		Date now = new Date();
		long day = 0;// 天数
		long hour = 0;// 小时
		long min = 0;// 分钟
		long sec = 0;// 秒
		try {
			long time1 = now.getTime();
			// time2 = time2 * 1000l;
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000));
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String rs = "";
		SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");//
		String d = format.format(time2);
		Date date = null;
		try {
			date = format.parse(d);// 把字符类型的转换成日期类型的！
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (now.getDate() - date.getDate() == 0) {// 当前时间和时间戳转换来的时间的天数对比
			DateFormat df2 = new SimpleDateFormat("HH:mm");
			rs = "今天  " + df2.format(time2);
			return rs;
		} else if (now.getDate() - date.getDate() == 1) {
			DateFormat df2 = new SimpleDateFormat("HH:mm");
			rs = "昨天  " + df2.format(time2);
			return rs;
		} else {
			DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			rs = df2.format(time2);
			return rs;
		}
	}

	public static long dateToMillsOne(String dateStr) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();

		try {
			c.setTime(sdf_all.parse(dateStr));
			return c.getTimeInMillis();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;
	}
	
	public static long dateToMillsTwo(String dateStr) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();

		try {
			c.setTime(sdf_all2.parse(dateStr));
			return c.getTimeInMillis();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;
	}

	public static String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format.format(new Date(System.currentTimeMillis()));
		return str;
	}

	// 判断手机号
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9])|(14[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 检查SDK
	 * 
	 * @return
	 */
	public static boolean isSFZ(String sfz) {
		Pattern p = Pattern.compile("\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z]");
		Matcher m = p.matcher(sfz);
		return m.matches();

	}

	// 判断电话
	public static boolean isTelephone(String phonenumber) {
		String phone = "0\\d{2,3}-\\d{7,8}";
		Pattern p = Pattern.compile(phone);
		Matcher m = p.matcher(phonenumber);
		return m.matches();
	}

	// 判断手机号
	public static boolean isMobileNO1(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9])|(14[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 检查SDK
	 * 
	 * @return
	 */
	public static boolean ExistSDCard1() {

		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	/**
	 * 获得字母、数字、空格的个数
	 * 
	 * @param s
	 * @return
	 */
	public static int getStringInfo(String s) {// 获得字母、数字、空格的个数
		char ch;
		int character = 0, blank = 0, number = 0;
		for (int i = 0; i < s.length(); i++) // for循环
		{
			ch = s.charAt(i);
			if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))// 统计字母
				character++; // 等同于character=character+1
			else if (ch == ' ') // 统计空格
				blank++; // 等同于blank=blank+1
			else if (ch >= '0' && ch <= '9') // 统计数字
				number++; // 等同于number=number+1;
		}
		return character + blank + number;
	}
	
	
	/**
	 * 字符串转整数
	 * 
	 * @param str
	 * @param defValue
	 * @return
	 */
	public static int toInt(String str, int defValue) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
		}
		return defValue;
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static int toInt(Object obj) {
		if (obj == null)
			return 0;
		return toInt(obj.toString(), 0);
	}

	/**
	 * 比较时间是否大于1天
	 * 
	 * @param lastTime
	 *            以前存的时间
	 * @param cureentTime
	 *            现在的系统时间
	 * @return true:大于1天 false:小于1天
	 */
	public static boolean compareTime(String lastTime, String cureentTime) {
		String[] lasts = lastTime.split("-");
		String[] cureents = cureentTime.split("-");
		int last0 = Integer.parseInt(lasts[0]);
		int cur0 = Integer.parseInt(cureents[0]);
		int last1 = Integer.parseInt(lasts[1]);
		int cur1 = Integer.parseInt(cureents[1]);
		int last2 = Integer.parseInt(lasts[2]);
		int cur2 = Integer.parseInt(cureents[2]);
		if (cur0 > last0) {
			return true;
		} else if (cur0 == last0) {// 年份相等
			if (cur1 > last1) {
				return true;
			} else if (cur1 == last1) {// 月份相等
				if (cur2 > last2) {
					return true;
				} else {
					return false;
				}
			}
		}
		return false;
	}

	private void sendSmsMessage(Context con,String address, String message)
			throws Exception {
		SmsManager smsMgr = SmsManager.getDefault();
		Intent sent = new Intent();
		sent.setAction("com.send");
		PendingIntent sentIntent = PendingIntent.getBroadcast(con, 0, sent, 0);
		Intent delivery = new Intent();
		delivery.setAction("com.delivery");
		PendingIntent deliveryIntent = PendingIntent.getBroadcast(con, 0,
				delivery, 0);
		smsMgr.sendTextMessage(address, null, message, sentIntent,
				deliveryIntent);
	}
	BroadcastReceiver send = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if ("com.send".equals(intent.getAction()))
				CustomToast.makeText(BaseApplication.getInstance(), "SMS send  success",
						Toast.LENGTH_LONG);
		}
	};
	BroadcastReceiver delivery = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if ("com.delivery".equals(intent.getAction()))
				CustomToast.makeText(BaseApplication.getInstance(), "SMS delivery success",
						Toast.LENGTH_LONG);
		}
	};
	
	/**
	 * 讲字符和数字转换为全角的
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		   char[] c = input.toCharArray();
		   for (int i = 0; i< c.length; i++) {
		       if (c[i] == 12288) {
		         c[i] = (char) 32;
		         continue;
		       }if (c[i]> 65280&& c[i]< 65375)
		          c[i] = (char) (c[i] - 65248);
		       }
		   return new String(c);
		}
	
	public static boolean isNumeric(String str){ 
	     Pattern pattern = Pattern.compile("[0-9]*"); 
	     return pattern.matcher(str).matches();    
	} 
	
	public static int getAndroidSDKVersion() {
		   int version = 0;
		   try {
		     version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
		   } catch (NumberFormatException e) {
		     LogUtils.e(e.toString());

		   }
		   return version;
		}
	
	public static String md5(String string) {
	    byte[] hash;
	    try {
	        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
	    } catch (NoSuchAlgorithmException e) {
	        throw new RuntimeException("Huh, MD5 should be supported?", e);
	    } catch (UnsupportedEncodingException e) {
	        throw new RuntimeException("Huh, UTF-8 should be supported?", e);
	    }

	    StringBuilder hex = new StringBuilder(hash.length * 2);
	    for (byte b : hash) {
	        if ((b & 0xFF) < 0x10) hex.append("0");
	        hex.append(Integer.toHexString(b & 0xFF));
	    }
	    return hex.toString();
	}
}
